import fs from 'fs';
import lodash from 'lodash';
import { createRequire } from 'module';
import path, { dirname } from 'path';
import { visualizer } from 'rollup-plugin-visualizer';
import { fileURLToPath } from 'url';
import { build } from 'vite';
import base from './base.js';
import { tr } from 'element-plus/es/locale/index.mjs';

// __dirname 在 ES6 模块中不可用，因此需要通过以下方式获取
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const require = createRequire(import.meta.url);

export default async function getConfigs(params = {}) {
  const buildStandAlone = process.argv.at(-1) === 'standalone';
  let { outDir, componentPath } = params ?? {};
  if (buildStandAlone) {
    outDir += '-standalone';
  }

  const componentPathBasic = `${componentPath}/basic`;
  const componentPathBussiness = `${componentPath}/bussiness`;
  const ext = ['tsx', 'ts', 'jsx', 'js', 'vue'];

  fs.rmSync(outDir, { recursive: true, force: true });
  const result = {};

  function getConfig(params) {
    const entry = { [params.name]: params.path };

    let o = {
      mode: 'production',
      publicDir: false,
      define: {},
      plugins: [
        {
          name: 'dependency-collector',
          generateBundle(options, bundle) {
            if (!buildStandAlone) return;
            for (const [fileName, chunkOrAsset] of Object.entries(bundle)) {
              if (chunkOrAsset.type === 'chunk') {
                const { imports, importedBindings } = chunkOrAsset;
                //  console.log('cd:', Object.keys(chunkOrAsset));
                //console.log(`组件 ${fileName} 依赖的第三方库:`, importedBindings);
                const persistent = imports.filter(
                  item =>
                    ['lodash', '@teld/q-components', 'vue'].includes(item) ===
                      false && item.includes('/') === false,
                );
                if (persistent.length > 0)
                  result[fileName.split('.')[0]] = persistent;
                //console.log(`组件 ${fileName} 依赖的第三方库:`, persistent);
              }
            }

            if (bundle['@teld/q-components']) {
              delete bundle['@teld/q-components'];
            }
          },
          closeBundle(err) {
            if (!buildStandAlone) return;
            if (err) {
              console.error(err);
              return;
            }

            fs.writeFileSync(
              path.join(
                __dirname,
                '../dist/umd-standalone/TComponents.deps.js',
              ),
              `window.TComponentDeps = ${JSON.stringify(result)}`,
            );
          },
        },
        visualizer({
          filename: './node_modules/.cache/visualizer/stats.html',
          open: false,
          gzipSize: true,
          brotliSize: true,
        }),
      ].filter(Boolean),
      optimizeDeps: {
        // exclude: ['@teld/q-components'],
      },
      build: {
        minify: true,
        cssCodeSplit: false,
        outDir: outDir,
        emptyOutDir: false,
        rollupOptions: {
          output: {
            exports: 'named',
            globals: {
              'vue': 'Vue',
              'vue-router': 'VueRouter',
              'vue-i18n': 'VueI18n',
              'lodash': '_',
              'echarts': 'echarts',
              'dayjs': 'dayjs',
              'echarts/charts': 'echarts/charts',
              'echarts/components': 'echarts/components',
              'echarts/renderers': 'echarts/renderers',
              '@teld/q-components': 'TQuasarBase',
            },
            entryFileNames(v) {
              return '[name].js';
            },
          },
          external: id => {

            if (id === 'vue-demi') {
              return false;
            }

            if (!buildStandAlone) {
              return /^vue/.test(id);
            }

            return (
              /^vue/.test(id) ||
              id === 'vue-router' ||
              id === 'vue-i18n' ||
              id === 'lodash' ||
              ///^lodash/.test(id) ||
              id === 'moment' ||
              id === 'dayjs' ||
              id === '@teld/q-components' ||
              // /^@teld\/q-components/.test(id) ||
              /^echarts/.test(id)
            );
          },
        },
        lib: {
          name: params.exportName ?? params.name,
          formats: [
            // 'cjs',
            // 'amd',
            'umd',
            // 'iife',
          ].filter(Boolean),
          entry: entry,
        },
      },
    };

    return o;
  }

  let entrys = [
    {
      exportName: 'TComponentsLang',
      name: 'lang',
      path: `${componentPath}/lang/index.js`,
    },
  ];
  if (!buildStandAlone) {
    entrys.push(
      {
        exportName: 'TComponents',
        name: 'index',
        path: `${componentPath}/index.js`,
      });
  }
  for (
    let i = 0, a = [componentPathBasic, componentPathBussiness];
    i < a.length;
    i++
  ) {
    const p = a[i];

    if (buildStandAlone) {
      entrys = entrys.concat([
        {
          exportName: 'TChartBar',
          name: 'TChartBar',
          path: `${componentPath}/bussiness/charts/bar/index.js`,
        },
        {
          exportName: 'TChartBarline',
          name: 'TChartBarline',
          path: `${componentPath}/bussiness/charts/barline/index.js`,
        },
        {
          exportName: 'TChartLine',
          name: 'TChartLine',
          path: `${componentPath}/bussiness/charts/line/index.js`,
        },
        {
          exportName: 'TChartPie',
          name: 'TChartPie',
          path: `${componentPath}/bussiness/charts/pie/index.js`,
        },
        {
          exportName: 'TChartRadar',
          name: 'TChartRadar',
          path: `${componentPath}/bussiness/charts/radar/index.js`,
        },
        {
          exportName: 'TChartStrip',
          name: 'TChartStrip',
          path: `${componentPath}/bussiness/charts/strip/index.js`,
        },
      ]);
      entrys = fs
        .readdirSync(p)
        .filter(v => fs.statSync(`${p}/${v}`).isDirectory())
        .map(k => {
          if (['.DS_Store'].includes(k)) {
            return [];
          }
          const v = `${p}/${k}`;
          let name = lodash.upperFirst(lodash.camelCase(k));
          return { name: `T${name}`, path: v };
        })
        .concat(entrys)
        .filter(Boolean);
    }
  }

  // entrys = [
  //   {
  //     exportName: 'TSelectHelper',
  //     name: 'TSelectHelper',
  //     path: `${componentPath}/bussiness/filter/index.js`,
  //     //path: `${componentPath}/basic/date/index.js`,
  //   },
  // ];

  const configs = [];
  let a = 0, b = 0;
  for (let i = 0; i < entrys.length; i++) {
    const e = entrys[i];
    // if (e.name == 'TPortal') continue
    if (e.path.indexOf('/bussiness') == -1) {
      console.log('基础组件数：' + a++, '总数：' + entrys.length);
    } else {
      console.log('业务组件数：' + b++, '总数：' + entrys.length);
    }
    console.dir(e)
  if (
    ext.some(v => e.path.endsWith(`.${v}`)) ||
    ext.some(v => fs.existsSync(e.path + '/index.' + v))
  ) {
    let o = await base(
      { command: 'build', mode: 'production', ssrBuild: false },
      getConfig(e),
    );
    configs.push(o);
  }
  }
  return configs;
}

let a = await getConfigs({
  componentPath: 'components',
  outDir: 'dist/umd',
});

for (let i = 0; i < a.length; i++) {
  await build(a[i]);
}
